#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) 2015  Data Enlighten Technology (Beijing) Co.,Ltd

import sys
import os
import traceback
import Lib.Logger.log4py as logging
from mj_parser import common_errors
#from xml.dom.minidom import parseString
#import xml.dom.minidom
from xml.dom import minidom

class BmwWebParser:

    def __init__(self, root_path='.'):
        self.logger = logging.get_logger('crawler', 'BmwWebSource')
        self.root_path = root_path
        self.conf_path = os.path.join(root_path, 'conf')
        self.cookie_file = os.path.join(self.conf_path, 'bmw_cookie.txt')
        self.data_path = os.path.join(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")),'data')

    def parse(self, vin):
        b = common_errors.ERR_SUCCESS
        res = {}
        vin_file = os.path.join(self.data_path, vin+'.txt')

        try:
            f_buff = ''
            if os.path.exists(vin_file) and os.path.isfile(vin_file):
                with open(vin_file, 'r', encoding='utf8') as f_vin:
                    f_buff = f_vin.read()

            # print(vin_file)
            print('===========================')
            # print(f_buff)
            DOMTree = minidom.parseString(f_buff)
            collection = DOMTree.documentElement

            items = collection.getElementsByTagName("item")

            typeCode = ''
            vinType = ''
            dev_series = ''
            line = ''
            body_type = ''
            steering = ''
            door_count = 0
            engine = ''
            cubical_capacity = ''
            power = ''
            transmision = ''
            gearbox = ''
            colour = ''
            upholstery = ''
            prod_date = ''
            pr_list = ''

            for item in items:
                if item.hasAttribute("key"):
                    key = item.getAttribute("key")
                    # print ("Title: %s" % short_vin)
                    if key == 'FAHRGESTELLNUMMER':
                        type = item.getElementsByTagName('STRING')[0]
                        vin_last7 = type.childNodes[0].data
                    if key == 'ausstattung':
                        vininfos = item.getElementsByTagName('ausstattung')[0]
                        childs = vininfos.childNodes
                        for child in childs:
                            # if child.nodeName == 'msFgstnrKomplett':
                            #     vin = child.firstChild.data if child.firstChild.data is not None else ''
                            if child.nodeName == 'msTypCode':
                                typeCode = child.firstChild.data if child.firstChild.data is not None else ''
                            if child.nodeName == 'msTyp':
                                vinType = child.firstChild.data if child.firstChild.data is not None else ''
                            if child.nodeName == 'msEBaureihe':
                                dev_series = child.firstChild.data if child.firstChild.data is not None else ''
                            if child.nodeName == 'msBaureihe':
                                line = child.firstChild.data if child.firstChild.data is not None else ''
                            if child.nodeName == 'msBauart':
                                body_type = child.firstChild.data if child.firstChild is not None and child.firstChild.data is not None else ''
                            if child.nodeName == 'msLenkung':
                                steering = child.firstChild.data if child.firstChild.data is not None else ''
                            if child.nodeName == 'msTueren':
                                door_count = child.firstChild.data if child.firstChild.data is not None else 0
                            if child.nodeName == 'msMotor':
                                engine = child.firstChild.data if child.firstChild.data is not None else ''
                            if child.nodeName == 'msHubraum':
                                cubical_capacity = child.firstChild.data if child.firstChild.data is not None else ''
                            if child.nodeName == 'msLeistung':
                                power = child.firstChild.data if child.firstChild.data is not None else ''
                            if child.nodeName == 'msAntrieb':
                                transmision = child.firstChild.data if child.firstChild.data is not None else ''
                            if child.nodeName == 'msGetriebe':
                                gearbox = child.firstChild.data if child.firstChild.data is not None else ''
                            if child.nodeName == 'msFarbe':
                                colour = child.firstChild.data if child.firstChild.data is not None else ''
                            if child.nodeName == 'msPolsterung':
                                upholstery = child.firstChild.data if child.firstChild.data is not None else ''
                            if child.nodeName == 'msProdDatum':
                                if child.firstChild is not None and child.firstChild.data is not None:
                                    prod_date = child.firstChild.data
                                else:
                                    prod_date = ''
                    # pr list print
                    if key == 'bedingungen':
                        prs = item.getElementsByTagName('JAXBVECTOR')[0]
                        bedingungens = prs.childNodes
                        for bedingungen in bedingungens:
                            childs = bedingungen.childNodes
                            pr1 = ''
                            pr2 = ''
                            pr3 = ''
                            lack1 = ''
                            lack = ''
                            af = ''
                            for child in childs:
                                if child.nodeName == 'msSalaArtSS':
                                    pr1 = child.firstChild.data
                                if child.nodeName == 'msSalaPrimanummerSS':
                                    pr2 = child.firstChild.data
                                if child.nodeName == 'msSalaHZaehlerSS':
                                    pr3 = child.firstChild.data
                                if len(pr1) > 0 and len(pr2) > 0 and len(pr3) > 0:
                                    pr_list += pr1 + pr2 + pr3 + '|'
                                    break
                                if child.nodeName == 'msLackCodeSS':
                                    lack2 = child.firstChild.data
                                if len(lack) > 0:
                                    pr_list += lack + '|'
                                    break
                                if child.nodeName == 'msAFCodeSS':
                                    af = child.firstChild.data
                                if len(af) > 0:
                                    pr_list += af + '|'
                                    break

            res["vin"] = str(vin)
            res["type_code"] = str(typeCode)
            res["type"] = str(vinType)
            res["dev_series"] = str(dev_series)
            res["line"] = str(line)
            res["body_type"] = str(body_type)
            res["steering"] = str(steering)
            res["door_count"] = int(door_count)
            res["engine"] = str(engine)
            res["cubical_capacity"] = str(cubical_capacity)
            res["power"] = str(power)
            res["transmision"] = str(transmision)
            res["gearbox"] = str(gearbox)
            res["colour"] = str(colour)
            res["upholstery"] = str(upholstery)
            res["prod_date"] = str(prod_date)
            res["pr_list"] = str(pr_list)

        except Exception as ex:
            try:
                b = common_errors.ERR_UNKNOWN
                exc_info = sys.exc_info()
                self.logger.error(ex)
            finally:
                traceback.print_exception(*exc_info)
                del exc_info

        none_str_num = 0
        for item in res.values():
            if item == '' or item == 0:
                none_str_num = none_str_num + 1

        if none_str_num >= 16:
            return common_errors.ERR_NO_VIN, res

        return b, res

    def get_value_by_list(self, key,list):
        if key in list:
            value = list[key] if list[key] is not None else ''
            return value
        else:
            return ''


if __name__ == '__main__':
    parser = BmwWebParser()
    # .\\data\\SALVA2BG2DH800209.json
    code, res = parser.parse('LBVKY1105JSE10207')
    print(code)
    print(res)